<template>
  <div style="padding: 10px">
    <a-card size="small">
      <a-row>
        <a-col :span="8" class="statistic-col">
          <Statistic
            :value="total"
            :value-style="{
              color: '#1890ff',
              fontSize: '32px',
              fontWeight: 600,
            }"
          >
            <template #title>
              <span>优惠合同数</span>
              <a-tooltip placement="right">
                <template #title>
                  <span>设置了优惠条款的合同总数</span>
                </template>
                <question-circle-outlined style="margin-left: 5px" />
              </a-tooltip>
            </template>
          </Statistic>
        </a-col>
        <a-col :span="8" class="statistic-col statistic-col-leftBor">
          <Statistic
            title="优惠租客数"
            :value="discountOwnerTotal"
            :value-style="{
              color: '#1890ff',
              fontSize: '32px',
              fontWeight: 600,
            }"
          ></Statistic>
        </a-col>
        <a-col :span="8" class="statistic-col statistic-col-leftBor">
          <Statistic
            title="减免金额"
            :value="discountPriceTotal"
            prefix="￥"
            :value-style="{
              color: '#1890ff',
              fontSize: '32px',
              fontWeight: 600,
            }"
          ></Statistic>
        </a-col>
      </a-row>
    </a-card>
    <a-card style="margin-top: 10px" size="small">
      <a-table
        :columns="columns"
        :dataSource="dataList"
        :pagination="pagination"
        :loading="tableLoading"
        @change="tableChange"
        rowKey="id"
        :scroll="{ x: 'max-content' }"
      >
        <template #title>
          <a-form
            layout="vertical"
            style="padding-top: 10px; padding-bottom: 20px"
          >
            <a-row :gutter="24">
              <a-col :span="4">
                <a-input
                  v-model:value="searchParams.owner_name"
                  placeholder="搜索租客名称"
                  allowClear
                />
              </a-col>
              <a-col :span="4">
                <a-select
                  v-model:value="searchParams.village_ids"
                  :options="villageList"
                  placeholder="请选择项目"
                  :allowClear="true"
                  mode="multiple"
                  optionFilterProp="label"
                  style="width: 100%"
                  @change="onVillageChange"
                >
                </a-select>
              </a-col>
              <a-col :span="4">
                <a-select
                  v-model:value="searchParams.build_ids"
                  :options="buildList"
                  placeholder="请选择楼宇"
                  :allowClear="true"
                  mode="multiple"
                  optionFilterProp="label"
                  style="width: 100%"
                >
                </a-select>
              </a-col>
              <a-col :span="4">
                <a-input
                  v-model:value="searchParams.contract_number"
                  placeholder="搜索合同编号"
                  allowClear
                />
              </a-col>
              <a-col :span="4">
                <a-select
                  placeholder="优惠类型"
                  v-model:value="searchParams.discount_type"
                  :options="discountTypeList"
                  allow-clear
                  style="width: 100%"
                />
              </a-col>
              <a-col :span="4">
                <a-space>
                  <a-button type="primary" @click="getDataList(true)">
                    搜索
                  </a-button>
                  <a-button @click="reset">重置</a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </template>
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.key == 'owner_name'">
            <a-button
              type="link"
              @click="showOwnerInfo(record.owner_id)"
              style="padding: 0; margin: 0"
              v-if="record.owner_name"
              >{{ record.owner_name }}</a-button
            >
            <span v-else>--</span>
          </template>
          <template v-if="column.key == 'room_info'">
            <span v-if="record.build_bind && record.build_bind.room.length > 0">
              <a
                v-for="room in record.build_bind.room"
                @click.stop="
                  roomClick(
                    room,
                    record.build_bind.room,
                    record.build_bind.village.id
                  )
                "
                >{{ room.layer_name + "-" + room.room_name
                }}<text v-if="record.build_bind.room.length > 1">, </text>
              </a>
            </span>
            <span v-else>--</span>
          </template>
          <template v-if="column.key == 'contract_number'">
            <a-button
              type="link"
              @click="showContractInfo(record.id)"
              style="padding: 0; margin: 0"
              v-if="record.contract_number"
              >{{ record.contract_number }}</a-button
            >
            <span v-else>--</span>
          </template>
          <template v-if="column.key == 'discount_type'">
            <template
              v-if="record.discount_type && record.discount_type.length > 0"
            >
              <div
                v-for="(item, index) of record.discount_type"
                :key="index"
                style="margin: 15px 0"
              >
                <a-tag
                  @click="discountClick(record.id, item)"
                  style="cursor: pointer"
                  :color="getTypesColor(item.discount_type)"
                >
                  {{ getTypeTxt(item.discount_type) }}
                </a-tag>
              </div>
            </template>
            <span v-else>--</span>
          </template>
          <template v-if="column.key == 'start_time'">
            <template
              v-if="record.discount_type && record.discount_type.length > 0"
            >
              <div
                v-for="(item, index) of record.discount_type"
                :key="index"
                style="margin: 15px 0"
              >
                {{ item.discount_start_time }}
              </div>
            </template>
            <span v-else>--</span>
          </template>
          <template v-if="column.key == 'end_time'">
            <template
              v-if="record.discount_type && record.discount_type.length > 0"
            >
              <div
                v-for="(item, index) of record.discount_type"
                :key="index"
                style="margin: 15px 0"
              >
                {{ item.discount_end_time }}
              </div>
            </template>
            <span v-else>--</span>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="currentOwnerId"
      @cancel="ownerDetailVisible = false"
    />

    <!--  合同详情  -->
    <ContractDetailDrawer
      :visible="contractDetailVisible"
      :id="currentContractId"
      :discountType="discountType"
      @handleCancel="
        () => {
          contractDetailVisible = false;
        }
      "
    />

    <!-- 房间详情 -->
    <RoomDrawer
      :visible="roomDetailVisible"
      @cancel="onRoomDrawerClose"
      :maxRoomNumber="maxRoomNumber"
      :detail="roomDetail"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  createVNode,
  reactive,
  toRefs,
  defineAsyncComponent,
} from "vue";
import request from "../../../common/utils/request";
import store from "../../../store/index";
import { Form, Statistic } from "ant-design-vue";
import { QuestionCircleOutlined } from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import OwnerDetailDrawer from "@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
const ContractDetailDrawer = defineAsyncComponent(() =>
  import("@/views/contract/ContractDetail/ContractDetailDrawer.vue")
);
import RoomDrawer from "@/components/village/RoomDrawer.vue";

const useForm = Form.useForm;

export default defineComponent({
  name: "BillRecord",
  components: {
    Statistic,
    QuestionCircleOutlined,
    OwnerDetailDrawer,
    ContractDetailDrawer,
    RoomDrawer,
  },
  setup() {
    const $router = useRouter();

    const state = reactive({
      page: 1,
      limit: 10,
      total: 0,
      dataList: [],
      tableLoading: false,
      discountOwnerTotal: 0,
      discountPriceTotal: 0,
      discountTypeList: [],

      currentOwnerId: 0,
      ownerDetailVisible: false,

      currentContractId: 0,
      contractDetailVisible: false,

      roomDetail: {},
      roomDetailVisible: false,
      maxRoomNumber: 0,

      discountType: "",
    });

    const searchParams = reactive({
      owner_name: "",
      contract_number: "",
      discount_type: null,
      village_ids: [],
      build_ids: [],
    });

    const { resetFields } = useForm(searchParams, {});

    const reset = () => {
      resetFields();
      getDataList(true);
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const tableChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };

    const getDataList = (init = false) => {
      state.tableLoading = true;
      if (init) {
        state.page = 1;
      }
      const params = {
        page: state.page,
        limit: state.limit,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
        if (
          params[key] &&
          Array.isArray(params[key]) &&
          params[key].length == 0
        ) {
          delete params[key];
        }
      }
      request
        .post("/org", "/contract/discountList", params)
        .then((res) => {
          state.dataList = res.list;
          state.total = res.total;
          state.discountOwnerTotal = res.discountOwnerTotal;
          state.discountPriceTotal = res.discountPriceTotal;
        })
        .finally(() => {
          state.tableLoading = false;
        });
    };

    const villageList = ref([]);
    const buildList = ref([]);
    const villageAndBuildList = ref([]);

    const getVillageList = () => {
      return new Promise((resolve) => {
        if (villageAndBuildList.value.length) {
          resolve();
        } else {
          request
            .get("/org", "/build/villageAndBuildList/v2", {
              checked: 1,
            })
            .then((res) => {
              villageAndBuildList.value = res.villageList;
              let vList = [];
              let bList = [];
              res.villageList.forEach((item) => {
                vList.push({
                  label: item.name,
                  value: item.id,
                });
                if (item.buildList && item.buildList.length > 0) {
                  item.buildList.forEach((build) => {
                    bList.push({
                      label: build.build_name,
                      value: build.id,
                    });
                  });
                }
              });
              villageList.value = vList;
              buildList.value = bList;
              resolve();
            });
        }
      });
    };

    // 切换项目时
    const onVillageChange = (value, option) => {
      let vbList = JSON.parse(JSON.stringify(villageAndBuildList.value));
      let bList = [];
      if (value.length > 0) {
        vbList = villageAndBuildList.value.filter((village) =>
          value.includes(village.id)
        );

        // 筛选项目时清除楼宇选中项
        searchParams.build_ids = [];
      }

      vbList.forEach((village) => {
        if (village.buildList && village.buildList.length > 0) {
          village.buildList.forEach((build) => {
            bList.push({
              label: build.build_name,
              value: build.id,
            });
          });
        }
      });
      buildList.value = bList;
    };

    const showOwnerInfo = (id) => {
      state.currentOwnerId = id;
      state.ownerDetailVisible = true;
    };

    const showContractInfo = (id) => {
      state.currentContractId = id;
      state.contractDetailVisible = true;
    };

    const getTypeTxt = (type) => {
      let result = "";
      if (state.discountTypeList.length > 0) {
        state.discountTypeList.forEach((item) => {
          if (item.value == type) {
            result = item.label;
          }
        });
      }
      return result;
    };

    // 获取最大房源号
    const getMaxRoomNumber = (list) => {
      let max = 0;
      for (let room of list) {
        if (max < Number(room.room_number)) {
          max = Number(room.room_number);
        }
      }
      return max;
    };

    const roomClick = (room, room_list, village_id) => {
      let roomData = room;
      roomData.village_id = village_id;
      state.roomDetail = roomData;
      state.maxRoomNumber = getMaxRoomNumber(room_list);
      state.roomDetailVisible = true;
    };

    const onRoomDrawerClose = () => {
      state.roomDetailVisible = false;
    };

    const getTypesColor = (type) => {
      let color = "";
      switch (type) {
        case "select_1":
          color = "#f7c881";
          break;
        case "select_2":
          color = "#108ee9";
          break;
        case "select_3":
          color = "#2db7f5";
          break;
        case "select_4":
          color = "#87d068";
          break;
        case "select_5":
          color = "#3b5999";
          break;
        default:
          break;
      }
      return color;
    };

    const discountClick = (id, item) => {
      state.discountType = item.discount_type;
      state.currentContractId = id;
      state.contractDetailVisible = true;
    };

    const init = () => {
      getVillageList().then(() => {
        store.dispatch("GetFilterOptions").then((res) => {
          console.log(res.discountType, "999999999999999999999");
          if (res && res.discountType) {
            state.discountTypeList = res.discountType;
          }
          getDataList();
        });
      });
    };

    init();

    return {
      pagination,
      columns,
      searchParams,
      ...toRefs(state),
      getDataList,
      reset,
      tableChange,

      villageList,
      buildList,
      onVillageChange,
      showOwnerInfo,
      showContractInfo,
      getTypeTxt,
      getMaxRoomNumber,
      roomClick,
      onRoomDrawerClose,
      getTypesColor,
      discountClick,
    };
  },
});

const columns = [
  {
    title: "租客名称",
    dataIndex: "owner_name",
    key: "owner_name",
    width: 200,
    fixed: "left",
  },
  {
    title: "项目名称",
    dataIndex: "village_name",
    key: "village_name",
    width: 200,
  },
  {
    title: "楼宇名称",
    dataIndex: "build_name",
    key: "build_name",
    width: 200,
  },
  {
    title: "房号",
    dataIndex: "room_info",
    key: "room_info",
    width: 200,
  },
  {
    title: "合同编号",
    dataIndex: "contract_number",
    key: "contract_number",
    width: 200,
  },
  {
    title: "签订日",
    dataIndex: "sign_time",
    key: "sign_time",
    width: 200,
  },
  {
    title: "优惠类型",
    dataIndex: "discount_type",
    key: "discount_type",
    width: 200,
  },
  {
    title: "优惠金额",
    dataIndex: "discount_price",
    key: "discount_price",
    width: 150,
    customRender: ({ text, record, index }) => {
      return text + "元";
    },
  },
  {
    title: "开始时间",
    dataIndex: "start_time",
    key: "start_time",
    width: 200,
  },
  {
    title: "结束时间",
    dataIndex: "end_time",
    key: "end_time",
    width: 200,
  },
];
</script>

<style lang="less" scoped>
.code-box {
  width: 100%;
  max-height: 800px;
  overflow-y: auto;
  .code {
    margin: 10px auto;
  }
}
.table-header {
  :deep(.ant-tabs-bar) {
    border-bottom: none;
  }
}
:deep(.ant-table.ant-table-bordered .ant-table-title) {
  border: 1px solid #fff;
}
:deep(.ant-table .ant-table-title) {
  padding: 0;
}
:deep(.ant-btn-link) {
  margin-right: 0;
}
.link {
  color: @primary-color;
  cursor: pointer;
}

:deep(.ant-statistic) {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.statistic-col {
  display: flex;
  justify-content: center;
}

.statistic-col-leftBor {
  border-left: 1px solid #e9e9e9;
}

:deep(.ant-tabs-top > .ant-tabs-nav::before) {
  border-bottom: none;
}
</style>
